package com.bjgzy.rating.mvp.presenter;

import android.app.Application;
import android.os.Message;

import com.bjgzy.rating.mvp.contract.RatingDetailContract;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.RatingDetailData;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;

import org.simple.eventbus.EventBus;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;


/**
 * @author xubo
 * @date 2018-8-7 16:51:51
 */
@ActivityScope
public class RatingDetailPresenter extends BasePresenter<RatingDetailContract.Model, RatingDetailContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public RatingDetailPresenter(RatingDetailContract.Model model, RatingDetailContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }
    public void getResearchById(int id, int configId, String userId) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("id", id);
        map.put("configId", configId);
        map.put("userId", userId);
        mModel.getResearchById(map)
                .retryWhen(new RetryWithDelay(2, 3))
                .compose(RxUtil.applySchedulers(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<RatingDetailData>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<RatingDetailData> commonData) {
                        if (commonData.isResult()) {
                            mRootView.update(commonData.getData());
                            Message msg = Message.obtain();
                            msg.what = EventBusTags.UPDATE_USER_WORKS_COUNT;
                            msg.arg1 = commonData.getData().getUserWorkCount();
                            EventBus.getDefault().post(msg, RouterHub.RATING_RATINGDETAILACTIVITY);

                        }else{
                            mRootView.showMessage(commonData.getMessage());
                        }
                    }
                });
    }

}
